﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using Wiwi.Models;
using Wiwi.ViewModels;

namespace Wiwi.Controllers
{
    public class AccountController : Controller
    {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl))
                    {
                        return Redirect(returnUrl);

                    }
                    else
                    {
                        //return RedirectToAction("Index", "Home");
                        return RedirectToAction("../Home/Profile");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);

        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff()
        {
            FormsService.SignOut();

            return RedirectToAction("Index", "Home");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        //public ActionResult Register()
        //{
        //    ViewBag.PasswordLength = MembershipService.MinPasswordLength;
        //    return View();
        //}
        public ActionResult Register(string fname,string lname, string email, string usr)
        {
            Registration reg = new Registration();
            reg.Firstname = fname;
            reg.Lastname = lname;
            reg.email = email;
            reg.UserName = usr;
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View(reg);
        }
        [HttpPost]
        public ActionResult Register(Registration reg)
        {
            if (ModelState.IsValid)
            {

                MembershipCreateStatus createStatus = MembershipService.CreateUser(reg.UserName, reg.Password, reg.email);
                if (createStatus == MembershipCreateStatus.Success)
                {
                    string[] str = new string[1];
                    str[0] = reg.UserName;
                    Roles.AddUsersToRole(str, "AppUsers");
                    A_UserTable ut = new A_UserTable();
                    ut.FName = reg.Firstname;
                    ut.Lname = reg.Lastname;
                    ut.UserID = new Guid(Membership.GetUser(reg.UserName).ProviderUserKey.ToString());
                    WiwiEntities1 db = new WiwiEntities1();
                    db.AddToA_UserTable(ut);
                    db.SaveChanges();
                    FormsService.SignIn(reg.UserName, false /* createPersistentCookie */);
                    return RedirectToAction("Editprofile", "Home");
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View(reg);
        }
        public static string GetErrorMessage(MembershipCreateStatus status)
        {
            switch (status)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "Username already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A username for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            ViewBag.PasswordLength = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }
        public ActionResult CheckusrNameAvailable(string UserName)
        {
            string strOut = "";
            int Taken = 0;
            MembershipUser usr = Membership.GetUser(UserName);
            if (usr != null)
            {
                strOut = "1";
                strOut += "?" + UserName + "1?" + UserName + DateTime.Now.Year.ToString();
                strOut += "?" + UserName + "2";
                Taken = 1;
            }
            else
            {
                strOut = "0";
            }
            return Json(strOut);
        }
        public ActionResult CheckEmailAvailable(string UserName)
        {
            string strOut = "";
            int Taken = 0;
            string strName = Membership.GetUserNameByEmail(UserName);
            if (strName != null)
            {
                if (strName !="") Taken = 1;
            }
            return Json(Taken.ToString());
        }

        public ActionResult PasswordForgot()
        {
            return View();
        }
        [HttpPost]
        public ActionResult PasswordForgot(Forgotpassword pass)
        {
            if (ModelState.IsValid)
            {
                MembershipUser usr = Membership.GetUser(pass.userID);
                string strName = "";
                if (usr == null)
                {
                    strName = Membership.GetUserNameByEmail(pass.userID);
                }
                if (usr == null && strName == "")
                {
                    pass.Respcode = 1;
                    pass.msg = "This user id / email is not registered on our system.";
                    return View(pass);
                }
                MembershipService.ChangePassword(usr.UserName, Membership.Provider.ResetPassword(usr.UserName, "a"), "1234567");
                pass.Respcode = 0;
                pass.msg = "Your password has been sent to your registered email account";
                return View(pass);
            }
            else
            {
                ModelState.AddModelError("", "Entered captcha value is invalid.");
                return View(pass);
            }
        }
    }
}
